<?php

namespace app\admin\model;

use houdunwang\crypt\Crypt;
use think\Loader;
use think\Model;
use think\Validate;

class Admin extends Model
{
    //主键
    protected $pk = 'admin_id';
    
    // 设置当前模型对应的完整数据表名称
    protected $table = 'blog_admin';

    public function login($data){
        //执行验证
        $validate = Loader::validate('Admin');
        //验证不通过
        if(!$validate->check($data)){
            //dump($validate->getError());
            return ['valid' => 0,'msg'=>$validate->getError()];
        }
        //比对用户名和密码
        $userinfo = $this->where('username',$data['username'])->where('password',Crypt::encrypt($data['password']))->find();
        if(!$userinfo){
            return ['valid' => 0,'msg'=>"用户名或者密码不正确"];
        }
        //保存session
        session("admin_id",$userinfo['admin_id']);
        session("username",$userinfo['username']);
        $this->where($this->pk,$userinfo['admin_id'])->update([
            'login_time'  => ['exp',time()],
            'login_number' => ['exp','login_number+1'],
        ]);
        return ['valid' => 1,'msg'=>"登陆成功"];
    }

    /**
     * 修改密码
     */
    public function updatepwd($data){
        $rule = [
            ['password','require','请输入原始密码'],
            ['new_password','require','请输入新密码'],
            ['confirm_password','require|confirm:new_password','请输入确认密码|两次密码不一致']
        ];
        $validate = new Validate($rule);
        $result   = $validate->check($data);
        if(!$result){
            return ['valid' => 0,'msg'=>$validate->getError()];
        }
        //判断原始密码是否正确
        $resultdate  = $this->where('admin_id',session('admin_id'))->where('password',Crypt::encrypt($data['password']))->find();
        if(!$resultdate){
            return ['valid' => 0,'msg'=>"原始密码错误，请重新输入"];
        }
        //修改密码
        $this->save(['password'=>Crypt::encrypt($data['new_password'])],[$this->pk=>session('admin_id')]);
        return ['valid' => 1,'msg'=>"密码修改成功"];
    }
}
